package com.haotian.pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

/**
 * 常用PDF操作函数整理
 *<p></p>
 * @author 张昊天
 * 2018年3月2日
 */
public class _PDFUtil {

	
		/**
		 * 在目标地址下载PDF 并 返回路径
		 * <p></p>
		 * @param fileUrl
		 * @param savePath
		 * @return
		 * @throws Exception
		 */
		public static String getTextFromPdfUrl(String fileUrl, String savePath) throws Exception {

			URL url = new URL(fileUrl);

			URLConnection conn = url.openConnection();

			InputStream inStream = conn.getInputStream();

			String fileName = UUID.randomUUID().toString();

			String pathFileName = savePath + "/" + fileName + ".pdf";

			FileOutputStream fs = new FileOutputStream(pathFileName);

			byte[] buffer = new byte[1204];
			int readlen;
			while ((readlen = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, readlen);
			}
			// 关闭文件流
			fs.flush();
			fs.close();
			inStream.close();

			return pathFileName;
		}
		
		
		/**
		 * 获取PDF内纯文本信息
		 * <p></p>
		 * @param filepath
		 * @param isDelFile
		 * @return
		 * @throws Exception
		 */
		public static String getTextFromPdfFile(String filepath, Boolean isDelFile) throws Exception {

			// 根据指定文件创建输入流
			RandomAccessBufferedFileInputStream stream = null;
			// 获取解析器的PDF文档对象
			PDDocument pdfdocument = null;
			// 生成PDF文档内容剥离器
			String contenttxt = null;
			try {
				stream = new RandomAccessBufferedFileInputStream(filepath);

				pdfdocument = PDDocument.load(stream);

				PDFTextStripper pdfstripper = new PDFTextStripper();

				pdfstripper.setSortByPosition(true);
				pdfstripper.setStartPage(1);
				pdfstripper.setEndPage(pdfdocument.getNumberOfPages());

				contenttxt = pdfstripper.getText(pdfdocument);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (pdfdocument != null)
					pdfdocument.close();
				if (stream != null)
					stream.close();

				if (isDelFile) {
					File deleteFile = new File(filepath);
					if (deleteFile.exists())
						deleteFile.delete();
				}

			}
			return contenttxt;
		}
	
	
	
}
